import Vue from 'vue';
import App from './app.vue';
import store from './store/index'
import VueRouter from 'vue-router';
import {routers, appRouter, otherRouter} from "./router";

Vue.config.silent = true;
Vue.config.devTools = true;

import './config/config'
import './config/components'

/** UI组件库 */
import 'ant-design-vue/dist/antd.css'
import Antd from 'ant-design-vue'

Vue.use(Antd);
import iView from 'iview';

Vue.use(iView);
import 'iview/dist/styles/iview.css';

/** 路由配置 */
const RouterConfig = {
  routes: routers
};

Vue.use(VueRouter);

store.commit('saveOriginRouter', appRouter);
const router = new VueRouter(RouterConfig);

let routerNames = [];
appRouter.forEach((item) => {
  let len = item.children.length;
  if (len === 1) {
    routerNames.push(item.children[0].name)
  } else {
    for (let i = 0; i < len; i++) {
      routerNames.push(item.children[i].name)
    }
  }
});
const CheckRouter = (to) => {
  let otherRouters = [...otherRouter.children];
  let others = [];
  otherRouters.map((item) => {
    others.push(item.name)
  });
  let currentRouterIndex = routerNames.indexOf(to);
  let passRouterNames = ['login', ...others];
  if (passRouterNames.indexOf(to) >= 0) {
    return true
  }
  if (currentRouterIndex < 0) {
    return false
  } else {
    return true
  }
};

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start();
  window.document.title = (to.meta.name ? to.meta.name + '-' : '') + '后台系统模板';
  if (!Vue.ls.get('user') && to.name !== 'login') {  // 判断是否已经登录且前往的页面不是登录页
    router.replace({
      name: 'login'
    });
    iView.LoadingBar.finish();
  } else if (Vue.ls.get('user') && to.name === 'login') {  // 判断是否已经登录且前往的是登录页
    next({
      name: 'home_index'
    });
    iView.LoadingBar.finish();
  } else {
    if (CheckRouter(to.name)) {
      next();
      iView.LoadingBar.finish();
    } else {
      Vue.ls.remove('user');
      Vue.ls.remove('password');
      Vue.ls.remove('hasGreet');
      Vue.ls.remove('access');
      store.commit('clearOpenedSubmenu');
      localStorage.clear();
      next({
        name: 'login'
      });
      iView.LoadingBar.finish();
    }
  }
});

router.afterEach(() => {
  iView.LoadingBar.finish();
  window.scrollTo(0, 0);
});

const go = (name, obj) => {
  router.push({
    name: name, //跳转页面name
    query: obj //参数
  })
};
Vue.prototype.$go = go;
// 状态管理
  new Vue({
    el: '#app',
    router: router,
    store: store,
    render: h => h(App),
    data: {
      currentPageName: ''
    },
    mounted() {
      this.currentPageName = this.$route.name;
    },
    created() {
      let tagsList = [];
      appRouter.map((item) => {
        if (item.children.length <= 1) {
          tagsList.push(item.children[0]);
        } else {
          tagsList.push(...item.children);
        }
      });
      this.$store.commit('setTagsList', tagsList);
    }
  });
